package org.hfy.utils;

import org.hfy.entity.Quotation;
import org.hfy.entity.QuotationItem;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 合同模板工具类
 * 
 * @author hfy
 * @version 1.0
 */
public class ContractTemplateUtil {

    /**
     * 生成完整的合同HTML内容
     */
    public static String generateContractHtml(Quotation quotation, String contractNo) {
        StringBuilder html = new StringBuilder();
        
        // 添加CSS样式
        html.append(generateCSS());
        
        // 合同头部
        html.append("<div class='contract-container'>");
        html.append("<div class='contract-header'>");
        html.append("<h1 class='contract-title'>PCB印制电路板加工合同</h1>");
        html.append("<div class='contract-no'>合同编号：").append(contractNo).append("</div>");
        html.append("</div>");
        
        // 合同基础信息
        html.append(generateBasicInfo(quotation));
        
        // 物料明细表
        html.append(generateItemsTable(quotation.getItems()));
        
        // 付款方式和总金额
        html.append(generatePaymentInfo(quotation));
        
        // 合同条款
        html.append(generateContractTerms());
        
        // 签字栏
        html.append(generateSignatureSection());
        
        html.append("</div>");
        
        return html.toString();
    }

    /**
     * 生成CSS样式
     */
    private static String generateCSS() {
        return "<style>" +
            ".contract-container {" +
                "font-family: 'SimSun', serif;" +
                "font-size: 12px;" +
                "line-height: 1.5;" +
                "color: #333;" +
                "max-width: 210mm;" +
                "margin: 0 auto;" +
                "padding: 20px;" +
            "}" +
            ".contract-header {" +
                "text-align: center;" +
                "margin-bottom: 30px;" +
                "border-bottom: 2px solid #333;" +
                "padding-bottom: 15px;" +
            "}" +
            ".contract-title {" +
                "font-size: 24px;" +
                "font-weight: bold;" +
                "margin: 0 0 10px 0;" +
                "color: #333;" +
            "}" +
            ".contract-no {" +
                "font-size: 14px;" +
                "font-weight: bold;" +
            "}" +
            ".basic-info {" +
                "margin-bottom: 25px;" +
            "}" +
            ".info-row {" +
                "display: flex;" +
                "margin-bottom: 8px;" +
                "align-items: center;" +
            "}" +
            ".info-label {" +
                "font-weight: bold;" +
                "min-width: 120px;" +
                "display: inline-block;" +
            "}" +
            ".info-value {" +
                "flex: 1;" +
            "}" +
            ".items-table {" +
                "width: 100%;" +
                "border-collapse: collapse;" +
                "margin-bottom: 25px;" +
                "font-size: 10px;" +
            "}" +
            ".items-table th," +
            ".items-table td {" +
                "border: 1px solid #333;" +
                "padding: 6px 4px;" +
                "text-align: center;" +
                "vertical-align: middle;" +
            "}" +
            ".items-table th {" +
                "background-color: #f5f5f5;" +
                "font-weight: bold;" +
            "}" +
            ".text-left {" +
                "text-align: left !important;" +
            "}" +
            ".text-right {" +
                "text-align: right !important;" +
            "}" +
            ".payment-info {" +
                "margin-bottom: 25px;" +
                "border: 1px solid #333;" +
                "padding: 15px;" +
            "}" +
            ".payment-title {" +
                "font-weight: bold;" +
                "font-size: 14px;" +
                "margin-bottom: 10px;" +
            "}" +
            ".total-amount {" +
                "font-weight: bold;" +
                "font-size: 16px;" +
                "color: #d32f2f;" +
            "}" +
            ".contract-terms {" +
                "margin-bottom: 30px;" +
            "}" +
            ".terms-title {" +
                "font-weight: bold;" +
                "font-size: 14px;" +
                "margin-bottom: 10px;" +
            "}" +
            ".terms-list {" +
                "padding-left: 20px;" +
            "}" +
            ".terms-list li {" +
                "margin-bottom: 5px;" +
            "}" +
            ".signature-section {" +
                "display: flex;" +
                "justify-content: space-between;" +
                "margin-top: 50px;" +
            "}" +
            ".signature-block {" +
                "text-align: center;" +
                "min-width: 200px;" +
            "}" +
            ".signature-line {" +
                "border-bottom: 1px solid #333;" +
                "height: 40px;" +
                "margin-bottom: 10px;" +
            "}" +
            "</style>";
    }

    /**
     * 生成合同基础信息
     */
    private static String generateBasicInfo(Quotation quotation) {
        StringBuilder html = new StringBuilder();
        
        html.append("<div class='basic-info'>");
        html.append("<div class='info-row'>");
        html.append("<span class='info-label'>甲方（客户）：</span>");
        html.append("<span class='info-value'>").append(quotation.getCustomerName()).append("</span>");
        html.append("</div>");
        
        html.append("<div class='info-row'>");
        html.append("<span class='info-label'>客户代码：</span>");
        html.append("<span class='info-value'>").append(quotation.getCustomerCode()).append("</span>");
        html.append("</div>");
        
        html.append("<div class='info-row'>");
        html.append("<span class='info-label'>联系人：</span>");
        html.append("<span class='info-value'>__________________</span>");
        html.append("</div>");
        
        html.append("<div class='info-row'>");
        html.append("<span class='info-label'>联系电话：</span>");
        html.append("<span class='info-value'>__________________</span>");
        html.append("</div>");
        
        html.append("<div class='info-row'>");
        html.append("<span class='info-label'>联系地址：</span>");
        html.append("<span class='info-value'>__________________</span>");
        html.append("</div>");
        
        html.append("<div class='info-row'>");
        html.append("<span class='info-label'>乙方（承制方）：</span>");
        html.append("<span class='info-value'>PCB印制电路板加工厂</span>");
        html.append("</div>");
        
        html.append("<div class='info-row'>");
        html.append("<span class='info-label'>业务员：</span>");
        html.append("<span class='info-value'>").append(quotation.getSalesperson()).append("</span>");
        html.append("</div>");
        
        html.append("<div class='info-row'>");
        html.append("<span class='info-label'>业务员电话：</span>");
        html.append("<span class='info-value'>__________________</span>");
        html.append("</div>");
        
        html.append("<div class='info-row'>");
        html.append("<span class='info-label'>业务员邮箱：</span>");
        html.append("<span class='info-value'>__________________</span>");
        html.append("</div>");
        
        html.append("<div class='info-row'>");
        html.append("<span class='info-label'>业务员地址：</span>");
        html.append("<span class='info-value'>__________________</span>");
        html.append("</div>");
        
        html.append("<div class='info-row'>");
        html.append("<span class='info-label'>订单日期：</span>");
        html.append("<span class='info-value'>").append(formatDate(quotation.getOrderDate())).append("</span>");
        html.append("</div>");
        
        html.append("</div>");
        
        return html.toString();
    }

    /**
     * 生成物料明细表
     */
    private static String generateItemsTable(List<QuotationItem> items) {
        StringBuilder html = new StringBuilder();
        
        html.append("<table class='items-table'>");
        html.append("<thead>");
        html.append("<tr>");
        html.append("<th style='width: 30px;'>序号</th>");
        html.append("<th style='width: 80px;'>产品名称</th>");
        html.append("<th style='width: 60px;'>物料编码</th>");
        html.append("<th style='width: 50px;'>板材</th>");
        html.append("<th style='width: 40px;'>板厚<br/>(mm)</th>");
        html.append("<th style='width: 40px;'>外铜</th>");
        html.append("<th style='width: 40px;'>内铜</th>");
        html.append("<th style='width: 60px;'>交货尺寸<br/>(mm)</th>");
        html.append("<th style='width: 50px;'>拼板</th>");
        html.append("<th style='width: 60px;'>表面处理</th>");
        html.append("<th style='width: 40px;'>阻焊</th>");
        html.append("<th style='width: 40px;'>字符</th>");
        html.append("<th style='width: 60px;'>过孔工艺</th>");
        html.append("<th style='width: 50px;'>测试</th>");
        html.append("<th style='width: 40px;'>数量</th>");
        html.append("<th style='width: 50px;'>单价<br/>(元)</th>");
        html.append("<th style='width: 50px;'>测试架费<br/>(元)</th>");
        html.append("<th style='width: 50px;'>工程费<br/>(元)</th>");
        html.append("<th style='width: 50px;'>样板费<br/>(元)</th>");
        html.append("<th style='width: 60px;'>合计金额<br/>(元)</th>");
        html.append("<th style='width: 60px;'>交期</th>");
        html.append("<th style='width: 80px;'>备注</th>");
        html.append("</tr>");
        html.append("</thead>");
        html.append("<tbody>");
        
        if (items != null && !items.isEmpty()) {
            for (QuotationItem item : items) {
                html.append("<tr>");
                html.append("<td>").append(item.getItemNo()).append("</td>");
                html.append("<td class='text-left'>").append(safePrint(item.getProductName())).append("</td>");
                html.append("<td>").append(safePrint(item.getMaterialCode())).append("</td>");
                html.append("<td>").append(safePrint(item.getBoardMaterial())).append("</td>");
                html.append("<td>").append(safePrint(item.getThickness())).append("</td>");
                html.append("<td>").append(safePrint(item.getOuterCopper())).append("</td>");
                html.append("<td>").append(safePrint(item.getInnerCopper())).append("</td>");
                html.append("<td>").append(safePrint(item.getDeliverySize())).append("</td>");
                html.append("<td>").append(safePrint(item.getPanelization())).append("</td>");
                html.append("<td>").append(safePrint(item.getSurfaceTreatment())).append("</td>");
                html.append("<td>").append(safePrint(item.getSolderMask())).append("</td>");
                html.append("<td>").append(safePrint(item.getCharacter())).append("</td>");
                html.append("<td>").append(safePrint(item.getViaProcess())).append("</td>");
                html.append("<td>").append(safePrint(item.getTesting())).append("</td>");
                html.append("<td>").append(item.getQuantity()).append("</td>");
                html.append("<td class='text-right'>").append(formatMoney(item.getUnitPrice())).append("</td>");
                html.append("<td class='text-right'>").append(formatMoney(item.getTestingFee())).append("</td>");
                
                // 从成本信息中获取工程费，如果没有则显示0
                BigDecimal engineeringFee = BigDecimal.ZERO;
                if (item.getCosts() != null && item.getCosts().getEngineeringFee() != null) {
                    engineeringFee = item.getCosts().getEngineeringFee();
                }
                html.append("<td class='text-right'>").append(formatMoney(engineeringFee)).append("</td>");
                
                html.append("<td class='text-right'>").append(formatMoney(item.getSampleFee())).append("</td>");
                html.append("<td class='text-right'>").append(formatMoney(item.getTotalAmount())).append("</td>");
                html.append("<td>").append(formatDate(item.getDeliveryDate())).append("</td>");
                html.append("<td class='text-left'>").append(safePrint(item.getItemRemark())).append("</td>");
                html.append("</tr>");
            }
        }
        
        html.append("</tbody>");
        html.append("</table>");
        
        return html.toString();
    }

    /**
     * 生成付款方式和总金额信息
     */
    private static String generatePaymentInfo(Quotation quotation) {
        StringBuilder html = new StringBuilder();
        
        html.append("<div class='payment-info'>");
        html.append("<div class='payment-title'>付款方式及金额信息</div>");
        
        html.append("<div class='info-row'>");
        html.append("<span class='info-label'>付款方式：</span>");
        html.append("<span class='info-value'>").append(quotation.getPaymentMethod()).append("</span>");
        html.append("</div>");
        
        html.append("<div class='info-row'>");
        html.append("<span class='info-label'>是否含税：</span>");
        html.append("<span class='info-value'>")
               .append(Boolean.TRUE.equals(quotation.getIsTaxIncluded()) ? "是（增值税票13%）" : "否")
               .append("</span>");
        html.append("</div>");
        
        html.append("<div class='info-row'>");
        html.append("<span class='info-label'>合同总金额：</span>");
        html.append("<span class='info-value total-amount'>")
               .append(formatMoney(quotation.getTotalAmount())).append(" 元</span>");
        html.append("</div>");
        
        if (Boolean.TRUE.equals(quotation.getIsTaxIncluded()) && quotation.getTotalTaxAmount() != null) {
            html.append("<div class='info-row'>");
            html.append("<span class='info-label'>含税总金额：</span>");
            html.append("<span class='info-value total-amount'>")
                   .append(formatMoney(quotation.getTotalTaxAmount())).append(" 元</span>");
            html.append("</div>");
        }
        
        html.append("</div>");
        
        return html.toString();
    }

    /**
     * 生成合同条款
     */
    private static String generateContractTerms() {
        StringBuilder html = new StringBuilder();
        
        html.append("<div class='contract-terms'>");
        html.append("<div class='terms-title'>合同条款</div>");
        html.append("<ol class='terms-list'>");
        html.append("<li>质量要求：按照甲方提供的技术要求和行业标准执行，确保产品质量合格。</li>");
        html.append("<li>交货时间：按照物料明细表中约定的交期执行，如有特殊情况需提前协商。</li>");
        html.append("<li>包装要求：采用标准防静电包装，确保产品在运输过程中不受损坏。</li>");
        html.append("<li>验收标准：甲方收货后3个工作日内完成验收，逾期视为验收合格。</li>");
        html.append("<li>付款条件：严格按照约定的付款方式执行，逾期付款需承担相应违约责任。</li>");
        html.append("<li>保密条款：双方对涉及的技术资料和商业信息承担保密义务。</li>");
        html.append("<li>违约责任：任何一方违约应承担相应的经济和法律责任。</li>");
        html.append("<li>争议解决：如发生争议，双方应友好协商解决，协商不成可向有管辖权的法院起诉。</li>");
        html.append("</ol>");
        html.append("</div>");
        
        return html.toString();
    }

    /**
     * 生成签字栏
     */
    private static String generateSignatureSection() {
        StringBuilder html = new StringBuilder();
        
        html.append("<div class='signature-section'>");
        html.append("<div class='signature-block'>");
        html.append("<div style='margin-bottom: 10px;'><strong>甲方（客户）</strong></div>");
        html.append("<div style='margin-bottom: 5px;'>签字：</div>");
        html.append("<div class='signature-line'></div>");
        html.append("<div style='margin-bottom: 5px;'>日期：</div>");
        html.append("<div class='signature-line'></div>");
        html.append("</div>");
        
        html.append("<div class='signature-block'>");
        html.append("<div style='margin-bottom: 10px;'><strong>乙方（承制方）</strong></div>");
        html.append("<div style='margin-bottom: 5px;'>签字：</div>");
        html.append("<div class='signature-line'></div>");
        html.append("<div style='margin-bottom: 5px;'>日期：</div>");
        html.append("<div class='signature-line'></div>");
        html.append("</div>");
        html.append("</div>");
        
        return html.toString();
    }

    /**
     * 安全打印字符串，处理null值
     */
    private static String safePrint(Object obj) {
        return obj == null ? "-" : obj.toString();
    }

    /**
     * 格式化金额
     */
    private static String formatMoney(BigDecimal amount) {
        if (amount == null) return "0.00";
        return String.format("%.2f", amount);
    }

    /**
     * 格式化日期
     */
    private static String formatDate(LocalDate date) {
        if (date == null) return "-";
        return date.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
    }
} 